<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>mongodb笔记(三) 创建、更新、删除文档 | 净土</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="mongodb 创建，mongodb 删除，mongodb 更新，mongodb 文档">
<meta property="og:type" content="article">
<meta property="og:title" content="mongodb笔记(三) 创建、更新、删除文档">
<meta property="og:url" content="http://howiefh.github.io/2014/05/04/mongodb-note-3-creating-updating-and-deleting-documents/index.html">
<meta property="og:site_name" content="净土">
<meta property="og:description" content="mongodb 创建，mongodb 删除，mongodb 更新，mongodb 文档">
<meta property="og:updated_time" content="2014-12-24T07:55:06.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="mongodb笔记(三) 创建、更新、删除文档">
<meta name="twitter:description" content="mongodb 创建，mongodb 删除，mongodb 更新，mongodb 文档">
  
    <link rel="alternative" href="/atom.xml" title="净土" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.ico">
  
  <link href="http://fonts.useso.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  <link rel="stylesheet" href="/css/style.css" type="text/css">
  
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-40492061-1', 'auto');
ga('send', 'pageview');

</script>


  
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "//hm.baidu.com/hm.js?56d2899c5e919fbf4a7b00de5d1c31dd";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>


</head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">净土</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/" id="subtitle">乐不在外而在心，心以为乐，则是境皆乐；心以为苦，则无境不苦。</a>
        </h2>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-github-link" class="nav-icon" href="https://github.com/howiefh" title="Github" target="_blank"></a>
        
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed" target="_blank"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://howiefh.github.io"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-mongodb-note-3-creating-updating-and-deleting-documents" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    
<a href="/2014/05/04/mongodb-note-3-creating-updating-and-deleting-documents/" class="article-date">
  <time datetime="2014-05-04T03:21:38.000Z" itemprop="datePublished">2014-05-04</time>
</a>


    
  <div class="article-category">
    <a class="article-category-link" href="/categories/Database/">Database</a>►<a class="article-category-link" href="/categories/Database/MongoDB/">MongoDB</a>
  </div>

  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      mongodb笔记(三) 创建、更新、删除文档
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
		
		<div id="toc" class="toc-article">
			<h2 class="toc-title"><span>Contents</span></h2>
		
			<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#插入并保存文档"><span class="toc-number">1.</span> <span class="toc-text">插入并保存文档</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#批量插入"><span class="toc-number">1.1.</span> <span class="toc-text">批量插入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#插入原理"><span class="toc-number">1.2.</span> <span class="toc-text">插入原理</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#删除文档"><span class="toc-number">2.</span> <span class="toc-text">删除文档</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#删除速度"><span class="toc-number">2.1.</span> <span class="toc-text">删除速度</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#更新文档"><span class="toc-number">3.</span> <span class="toc-text">更新文档</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#文档替换"><span class="toc-number">3.1.</span> <span class="toc-text">文档替换</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用修改器"><span class="toc-number">3.2.</span> <span class="toc-text">使用修改器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#upsert"><span class="toc-number">3.3.</span> <span class="toc-text">upsert</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#save_shell帮助程序"><span class="toc-number">3.4.</span> <span class="toc-text">save shell帮助程序</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#更新多个文档"><span class="toc-number">3.5.</span> <span class="toc-text">更新多个文档</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#返回已更新文档"><span class="toc-number">3.6.</span> <span class="toc-text">返回已更新文档</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#设置写问题"><span class="toc-number">4.</span> <span class="toc-text">设置写问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#连接"><span class="toc-number">5.</span> <span class="toc-text">连接</span></a></li></ol>
		
		</div>
		
        <h2 id="插入并保存文档">插入并保存文档</h2><h3 id="批量插入">批量插入</h3><p>可以使用<code>batchInsert()</code>进行批量插入，如果是导入原始数据可以使用<code>mongoimport</code>。批量插入只能插入一个集合，不能插入一次对多个集合操作。</p>
<p>当前版本mongodb接收的最大消息长度为16MB，所以使用批量插入会有所限制。不过一些驱动会将消息拆分为48MB。</p>
<a id="more"></a>
<figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.foo.batchInsert<span class="params">([&#123;<span class="string">"_id"</span>:<span class="number">0</span>&#125;,&#123;<span class="string">"_id"</span>:<span class="number">1</span>&#125;,&#123;<span class="string">"_id"</span>:<span class="number">2</span>&#125;,&#123;<span class="string">"_id"</span>:<span class="number">3</span>&#125;])</span></span><br><span class="line">db.foo.batchInsert<span class="params">([&#123;<span class="string">"_id"</span>:<span class="number">0</span>&#125;,&#123;<span class="string">"_id"</span>:<span class="number">1</span>&#125;,&#123;<span class="string">"_id"</span>:<span class="number">1</span>&#125;,&#123;<span class="string">"_id"</span>:<span class="number">2</span>&#125;])</span></span><br></pre></td></tr></table></figure>
<p>第二条只能插入两个文档，可以使用<code>continueOnError</code>选项继续插入，如果使用该选项，第二条命令将会插入三个文档。shell不支持该选项，但是驱动支持。</p>
<h3 id="插入原理">插入原理</h3><p>插入数据只对是否包含”_id”和文档是否超过16MB进行检查。主流语言的驱动在插入数据时都会进行有效性检查。插入并不执行代码，可以预防注入攻击。</p>
<h2 id="删除文档">删除文档</h2><figure class="highlight cmake"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.foo.<span class="keyword">remove</span>(&#123;&#125;)</span><br><span class="line">db.foo.<span class="keyword">remove</span>(&#123;<span class="string">"bar"</span>:<span class="string">"hello"</span>&#125;)</span><br></pre></td></tr></table></figure>
<p>第一条命令会删除集合foo中所有文档，但是不删除集合。第二条命令删除所有bar为hello的文档。删除是永久的，不能撤销，也不能恢复。</p>
<h3 id="删除速度">删除速度</h3><p>使用<code>db.foo.drop()</code>代替<code>db.foo.remove();db.findOne();</code>要快很多，但是不能有限制条件，连同索引整个集合都被删除。</p>
<h2 id="更新文档">更新文档</h2><h3 id="文档替换">文档替换</h3><p>update要做的首先是查询，然后是替换。<br><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">"<span class="attribute">_id</span>" : <span class="value">ObjectId(<span class="string">"4b2b9f67a1f631733d917a7a"</span>)</span>,</span><br><span class="line">"<span class="attribute">name</span>" : <span class="value"><span class="string">"joe"</span></span>,</span><br><span class="line">"<span class="attribute">friends</span>" : <span class="value"><span class="number">32</span></span>,</span><br><span class="line">"<span class="attribute">enemies</span>" : <span class="value"><span class="number">2</span></span><br><span class="line"></span>&#125;</span><br></pre></td></tr></table></figure></p>
<p>对于上面文档要把friends和enemies放在relationships里，可以执行<br><figure class="highlight q"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">var</span> joe = db.users.findOne(&#123;<span class="string">"name"</span> : <span class="string">"joe"</span>&#125;);</span><br><span class="line">joe.relationships = &#123;<span class="string">"friends"</span> : joe.friends, <span class="string">"enemies"</span> : joe.enemies&#125;;</span><br><span class="line">joe.username = joe.name;</span><br><span class="line"><span class="keyword">delete</span> joe.friends;</span><br><span class="line"><span class="keyword">delete</span> joe.enemies;</span><br><span class="line"><span class="keyword">delete</span> joe.name;</span><br><span class="line">db.users.<span class="keyword">update</span>(&#123;<span class="string">"name"</span> : <span class="string">"joe"</span>&#125;, joe);</span><br></pre></td></tr></table></figure></p>
<p>现在执行一次find，文档变成了<br><figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">"<span class="attribute">_id</span>" : <span class="value">ObjectId(<span class="string">"4b2b9f67a1f631733d917a7a"</span>)</span>,</span><br><span class="line">"<span class="attribute">username</span>" : <span class="value"><span class="string">"joe"</span></span>,</span><br><span class="line">"<span class="attribute">relationships</span>" : <span class="value">&#123;</span><br><span class="line">"<span class="attribute">friends</span>" : <span class="value"><span class="number">32</span></span>,</span><br><span class="line">"<span class="attribute">enemies</span>" : <span class="value"><span class="number">2</span></span><br><span class="line"></span>&#125;</span><br><span class="line"></span>&#125;</span><br></pre></td></tr></table></figure></p>
<p>但有时update查询时可能会有多个匹配<br><figure class="highlight aspectj"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;<span class="string">"_id"</span> : ObjectId(<span class="string">"4b2b9f67a1f631733d917a7b"</span>), <span class="string">"name"</span> : <span class="string">"joe"</span>, <span class="string">"age"</span> : 65&#125;,</span><br><span class="line">&#123;<span class="string">"_id"</span> : ObjectId(<span class="string">"4b2b9f67a1f631733d917a7c"</span>), <span class="string">"name"</span> : <span class="string">"joe"</span>, <span class="string">"age"</span> : 20&#125;,</span><br><span class="line">&#123;<span class="string">"_id"</span> : ObjectId(<span class="string">"4b2b9f67a1f631733d917a7d"</span>), <span class="string">"name"</span> : <span class="string">"joe"</span>, <span class="string">"age"</span> : 49&#125;,</span><br></pre></td></tr></table></figure></p>
<p>执行下面命令更新年龄<br><figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">joe = <span class="keyword">db</span>.people.findOne(&#123;<span class="string">"name"</span> : <span class="string">"joe"</span>, <span class="string">"age"</span> : 20&#125;);</span><br><span class="line">joe.age++;</span><br><span class="line"><span class="keyword">db</span>.people.<span class="keyword">update</span>(&#123;<span class="string">"name"</span> : <span class="string">"joe"</span>&#125;, joe);</span><br></pre></td></tr></table></figure></p>
<p>会报<code>E11001 duplicate key on update</code>的错误，原因是update先找到了第一个65的joe，要更新的时候，因为已经有了一个相同<code>_id</code>所以报错了。最好的做法就是在更新的时候使用每个文档都唯一的<code>_id</code>进行查询。</p>
<h3 id="使用修改器">使用修改器</h3><ul>
<li><p><code>$set</code><br>  用来指定一个键的值。如果这个键不存在，则创建它。用$set甚至可以修改键的数据类型。也可以用$set修改内嵌文档。</p>
<figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">db</span>.users.<span class="keyword">update</span>(&#123;<span class="string">"name"</span> : <span class="string">"joe"</span>&#125;, &#123;<span class="string">"$set"</span> : &#123;<span class="string">"favorite book"</span> : [<span class="string">"Cat's Cradle"</span>, <span class="string">"Foundation Trilogy"</span>, <span class="string">"Ender's Game"</span>]&#125;&#125;)</span><br></pre></td></tr></table></figure>
</li>
<li><p><code>$unset</code><br>  将键完全删除。</p>
<figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">db</span>.users.<span class="keyword">update</span>(&#123;<span class="string">"name"</span> : <span class="string">"joe"</span>&#125;, &#123;<span class="string">"$unset"</span> : &#123;<span class="string">"favorite book"</span> : 1&#125;&#125;)</span><br></pre></td></tr></table></figure>
</li>
<li><p><code>$inc</code><br>  用来增加已有键的值，或者在键不存在时创建一个键。$inc只能用于整数、长整数或双精度浮点数。要是用在其他类型的数据上就会导致操作失败。另外$inc键的值必须是数字。</p>
<figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">db</span>.games.<span class="keyword">update</span>(&#123;<span class="string">"game"</span> : <span class="string">"pinball"</span>, <span class="string">"user"</span> : <span class="string">"joe"</span>&#125;,&#123;<span class="string">"$inc"</span> : &#123;<span class="string">"score"</span> : 50&#125;&#125;)</span><br></pre></td></tr></table></figure>
</li>
<li><p><code>$push</code><br>  会向已有的数组末尾加入一个元素，要是没有就会创建一个新的数组。<br>  比如向博客中添加评论，如果数组comments不存在，下面语句会创建这个数组，如果存在，则是向数组末尾再添加一个评论</p>
<figure class="highlight perl"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.blog.posts.update(&#123;<span class="string">"title"</span> : <span class="string">"A blog post"</span>&#125;, &#123;<span class="string">"<span class="variable">$push</span>"</span> : &#123;<span class="string">"comments"</span> :&#123;<span class="string">"name"</span> : <span class="string">"joe"</span>, <span class="string">"email"</span> : <span class="string">"joe<span class="variable">@example</span>.com"</span>,<span class="string">"content"</span> : <span class="string">"nice post."</span>&#125;&#125;&#125;)</span><br></pre></td></tr></table></figure>
<p>  和<code>$each</code>一起使用，可以一次想数组添加几个元素</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.stock.ticker.update(&#123;<span class="string">"_id"</span> : <span class="string">"GOOG"</span>&#125;, &#123;<span class="string">"<span class="variable">$push</span>"</span> : &#123;<span class="string">"hourly"</span> : &#123;<span class="string">"<span class="variable">$each</span>"</span> : [<span class="number">562.776</span>, <span class="number">562.790</span>, <span class="number">559.123</span>]&#125;&#125;&#125;)</span><br><span class="line">`</span><br></pre></td></tr></table></figure>
<p>  可以通过<code>$sort</code>排序，然后通过<code>$slice</code>取出前十</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.movies.find(&#123;<span class="string">"genre"</span> : <span class="string">"horror"</span>&#125;, &#123;<span class="string">"<span class="variable">$push</span>"</span> : &#123;<span class="string">"top10"</span> : &#123; <span class="string">"<span class="variable">$each</span>"</span> : [&#123;<span class="string">"name"</span> : <span class="string">"Nightmare on Elm Street"</span>, <span class="string">"rating"</span> : <span class="number">6.6</span>&#125;, &#123;<span class="string">"name"</span> : <span class="string">"Saw"</span>, <span class="string">"rating"</span> : <span class="number">4.3</span>&#125;], <span class="string">"<span class="variable">$slice</span>"</span> : -<span class="number">10</span>, <span class="string">"<span class="variable">$sort</span>"</span> : &#123;<span class="string">"rating"</span> : -<span class="number">1</span>&#125;&#125;&#125;&#125;)</span><br></pre></td></tr></table></figure>
</li>
<li><p><code>$addToSet</code><br>  可以避免重复。和$each组合起来，可以添加多个不同的值。<br>  如果把数组当做集合，里面的值就不能相同了，这时可以用<code>$push</code>和<code>$ne</code>，<code>db.papers.update({&quot;authors cited&quot; : {&quot;$ne&quot; : &quot;Richie&quot;}}, {$push : {&quot;authors cited&quot; : &quot;Richie&quot;}})</code> ，如果不存在 Richie,则会插入，但是有些情况，<code>$ne</code>就不能很好工作了。<br>  只有当数组emails中不存在joe@gmail.com时，才会添加进去。</p>
<figure class="highlight perl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.users.update(&#123;<span class="string">"_id"</span> : ObjectId(<span class="string">"4b2d75476cc613d5ee930164"</span>)&#125;, &#123;<span class="string">"<span class="variable">$addToSet</span>"</span> : &#123;<span class="string">"emails"</span> : <span class="string">"joe<span class="variable">@gmail</span>.com"</span>&#125;&#125;)</span><br><span class="line">db.users.update(&#123;<span class="string">"_id"</span> : ObjectId(<span class="string">"4b2d75476cc613d5ee930164"</span>)&#125;, &#123;<span class="string">"<span class="variable">$addToSet</span>"</span> : &#123;<span class="string">"emails"</span> : &#123;<span class="string">"<span class="variable">$each</span>"</span> : [<span class="string">"joe<span class="variable">@php</span>.net"</span>, <span class="string">"joe<span class="variable">@example</span>.com"</span>, <span class="string">"joe<span class="variable">@python</span>.org"</span>]&#125;&#125;&#125;)</span><br></pre></td></tr></table></figure>
</li>
<li><p><code>$pop</code><br>  这个修改器可以从数组任何一端删除元素。{$pop:{key:1}}从数组末尾删除一个元素，{$pop:{key:-1}}从头部删除。</p>
</li>
<li><p><code>$pull</code><br>  会将所有匹配的部分删除。</p>
<figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">db</span>.lists.insert(&#123;<span class="string">"todo"</span> : [<span class="string">"dishes"</span>, <span class="string">"laundry"</span>, <span class="string">"dry cleaning"</span>]&#125;) </span><br><span class="line"><span class="keyword">db</span>.lists.<span class="keyword">update</span>(&#123;&#125;, &#123;<span class="string">"$pull"</span> : &#123;<span class="string">"todo"</span> : <span class="string">"laundry"</span>&#125;&#125;)</span><br></pre></td></tr></table></figure>
</li>
<li><p><code>$</code>定位操作符<br>  可以直接指定数组下标，但是有时候并不是直接就知道下标，所以可以使用定位操作符，它的作用就是定位已经匹配的元素。</p>
<figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">db</span>.blog.<span class="keyword">update</span>(&#123;<span class="string">"post"</span> : post_id&#125;, &#123;<span class="string">"$inc"</span> : &#123;<span class="string">"comments.0.votes"</span> : 1&#125;&#125;)</span><br><span class="line"><span class="keyword">db</span>.blog.<span class="keyword">update</span>(&#123;<span class="string">"comments.author"</span> : <span class="string">"John"</span>&#125;, &#123;<span class="string">"$set"</span> : &#123;<span class="string">"comments.$.author"</span> : <span class="string">"Jim"</span>&#125;&#125;)</span><br></pre></td></tr></table></figure>
</li>
<li><p>修改器速度<br>  如果修改器操作后集合大小会改变，速度会稍慢一些。如果是很大的数组，速度也会比较慢。有时候可以考虑将内嵌数组独立到一个集合中。</p>
</li>
</ul>
<h3 id="upsert">upsert</h3><p>upsert是一种特殊的更新。当没有符合条件的文档，就以这个条件和更新文档为基础创建一个新的文档，如果找到匹配的文档就正常的更新。<br>使用upsert，既可以避免竞态问题，也可以减少代码量（update的第三个参数就表示这个upsert，参数为true时）<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">db.users.update(&#123;<span class="string">"rep"</span> : <span class="number">25</span>&#125;, &#123;<span class="string">"<span class="variable">$inc</span>"</span> : &#123;<span class="string">"rep"</span> : <span class="number">3</span>&#125;&#125;, <span class="literal">true</span>)</span><br></pre></td></tr></table></figure></p>
<p>执行命令之后rep为28</p>
<h3 id="save_shell帮助程序">save shell帮助程序</h3><p>save是shell函数，可以在文档不存在时插入，存在时更新。只有一个参数文档。如果文档含有<code>_id</code>，save就会调用upsert。否则，调用插入。<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">var</span> x = db<span class="class">.foo</span><span class="class">.findOne</span>()</span><br><span class="line">x<span class="class">.num</span> = <span class="number">42</span></span><br><span class="line">db<span class="class">.foo</span><span class="class">.save</span>(x)</span><br></pre></td></tr></table></figure></p>
<p>最后一条语句和<br><figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">db</span>.foo.<span class="keyword">update</span>(&#123;<span class="string">"_id"</span>:x._id&#125;,x)</span><br></pre></td></tr></table></figure></p>
<p>效果一样</p>
<h3 id="更新多个文档">更新多个文档</h3><p>update第四个参数为true就是对多个文档更新，默认参数将来可能改变，所以最好总是指定此参数。<br><figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">db.count.update(&#123;<span class="string">x :</span> <span class="number">1</span>&#125;, &#123;<span class="string">$inc :</span> &#123;<span class="string">x :</span> <span class="number">1</span>&#125;&#125;, <span class="literal">false</span>, <span class="literal">true</span>)</span><br><span class="line">db.runCommand(&#123;<span class="string">getLastError :</span> <span class="number">1</span>&#125;)</span><br></pre></td></tr></table></figure></p>
<p>第一条命令对所有x为1的加一，第二条命令查看更新了多少条。</p>
<h3 id="返回已更新文档">返回已更新文档</h3><p>将执行命令前的文档赋值给ps<br><figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ps = db.<span class="function"><span class="title">runCommand</span><span class="params">(&#123;<span class="string">"findAndModify"</span> : <span class="string">"processes"</span>,<span class="string">"query"</span> : &#123;<span class="string">"status"</span> : <span class="string">"READY"</span>&#125;, <span class="string">"sort"</span> : &#123;<span class="string">"priority"</span> : -<span class="number">1</span>&#125;, <span class="string">"update"</span> : &#123;<span class="string">"$set"</span> : &#123;<span class="string">"status"</span> : <span class="string">"RUNNING"</span>&#125;&#125;)</span></span></span><br></pre></td></tr></table></figure></p>
<p>将匹配到的文档从集合删除<br><figure class="highlight openscad"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">ps = db.runCommand<span class="params">(&#123;<span class="string">"findAndModify"</span> : <span class="string">"processes"</span>,</span><br><span class="line"><span class="string">"query"</span> : &#123;<span class="string">"status"</span> : <span class="string">"READY"</span>&#125;,</span><br><span class="line"><span class="string">"sort"</span> : &#123;<span class="string">"priority"</span> : -<span class="number">1</span>&#125;,</span><br><span class="line"><span class="string">"remove"</span> : <span class="literal">true</span>&#125;)</span>.value</span><br><span class="line">do_something<span class="params">(ps)</span></span><br></pre></td></tr></table></figure></p>
<ul>
<li>findAndModify<br>  字符串, 集合名</li>
<li>query<br>  查询文档; 用来检索文档的条件</li>
<li>sort<br>  排序结果的条件</li>
<li>update<br>  修改器文档，对所找到的文档执行更新。</li>
<li>remove<br>  布尔类型，表示是否删除文档</li>
<li>new<br>  布尔类型，表示返回的是更新前的还是更新后的文档，默认是更新前的。</li>
<li>fields<br>  文档返回的字段(可选)</li>
<li>upsert<br>  布尔类型，是否执行upsert，默认false<br>remove和update必须有一个。<br>执行会慢一些。如果多个线程之间有竞争关系，使用findAndModify是很有必要的。</li>
</ul>
<h2 id="设置写问题">设置写问题</h2><p>在2012年mongodb改变了默认的写数据的安全设置。之前默认是没有应答的，现在有。如果驱动中有一个MongoClient类，那么他默认写是安全的。</p>
<h2 id="连接">连接</h2><p>mongodb为每一个连接创建一个队列，如果有两个线程，一个线程刚执行完插入操作，另一个线程不一定能够立刻查询到刚刚插入到内容。但这种情况很难手动模拟。很多驱动程序都由一个连接来处理一系列的请求。</p>

      
    </div>
    <footer class="article-footer">
	  
	  <!-- 百度分享 Start -->
	  <div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a><a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a><a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博"></a><a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网"></a><a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a></div>
	  <!-- 百度分享 End -->
	  
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/MongoDB/">MongoDB</a></li></ul>

	  
<span>
Updated:<time datetime="2014-12-24T07:55:06.000Z" itemprop="dateModified">2014-12-24</time>
</span>


    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2014/05/08/mongodb-note-4-querying/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          mongodb笔记(四) 查询
        
      </div>
    </a>
  
  
    <a href="/2014/04/30/mongodb-note-2-start-mongodb/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">mongodb笔记(二) 入门</div>
    </a>
  
</nav>

  
</article>



<!-- 多说评论框 start -->

<section id="comments">
  <div class="ds-thread"  data-thread-key="/2014/05/04/mongodb-note-3-creating-updating-and-deleting-documents/" data-title="mongodb笔记(三) 创建、更新、删除文档" data-url="http://howiefh.github.io/2014/05/04/mongodb-note-3-creating-updating-and-deleting-documents/" id="ds_thread">
    <noscript>Please enable JavaScript to view the <a href="//duoshuo.com/?ref_noscript">comments powered by duoshuo.</a></noscript>
  </div>
</section>

<!-- 多说评论框 end -->
</section>
        
          
  <div id="toc" class="toc-aside">
  <h2 class="toc-title">Contents</h2>
    
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#插入并保存文档"><span class="toc-number">1.</span> <span class="toc-text">插入并保存文档</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#批量插入"><span class="toc-number">1.1.</span> <span class="toc-text">批量插入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#插入原理"><span class="toc-number">1.2.</span> <span class="toc-text">插入原理</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#删除文档"><span class="toc-number">2.</span> <span class="toc-text">删除文档</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#删除速度"><span class="toc-number">2.1.</span> <span class="toc-text">删除速度</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#更新文档"><span class="toc-number">3.</span> <span class="toc-text">更新文档</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#文档替换"><span class="toc-number">3.1.</span> <span class="toc-text">文档替换</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用修改器"><span class="toc-number">3.2.</span> <span class="toc-text">使用修改器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#upsert"><span class="toc-number">3.3.</span> <span class="toc-text">upsert</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#save_shell帮助程序"><span class="toc-number">3.4.</span> <span class="toc-text">save shell帮助程序</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#更新多个文档"><span class="toc-number">3.5.</span> <span class="toc-text">更新多个文档</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#返回已更新文档"><span class="toc-number">3.6.</span> <span class="toc-text">返回已更新文档</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#设置写问题"><span class="toc-number">4.</span> <span class="toc-text">设置写问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#连接"><span class="toc-number">5.</span> <span class="toc-text">连接</span></a></li></ol>
    
  </div>

<aside id="sidebar">

  
    
<div class="widget-wrap">
  <h3 class="widget-title">ABOUT ME</h3>
  <ul class="widget about-me">
    
    <li><img class="author" title="About me" src="http://fh-1.qiniudn.com/okal-eltocat.jpg" /></li>
    
    
    <li>Hi,I'm FengHao.</li>
    
    <li>I'll share something interesting and my learning experience with you at this blog.</li>
    
    <li>前博客:<a href="http://hi.baidu.com/idea_star" target="_BLANK">百度空间</a></li>
    
  </ul>
</div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Categories</h3>
    <div class="widget">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Android/">Android</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/C/">C</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Database/">Database</a><span class="category-list-count">13</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/Database/MongoDB/">MongoDB</a><span class="category-list-count">10</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Database/MySQL/">MySQL</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/Eclipse/">Eclipse</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/FTP/">FTP</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Git/">Git</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Hexo/">Hexo</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Java/">Java</a><span class="category-list-count">20</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/Java/FreeMarker/">FreeMarker</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Java/Shiro/">Shiro</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/">JavaEE</a><span class="category-list-count">4</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/Hibernate/">Hibernate</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/JSP/">JSP</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaEE/Spring/">Spring</a><span class="category-list-count">2</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/JavaScript/">JavaScript</a><span class="category-list-count">5</span><ul class="category-list-child"><li class="category-list-item"><a class="category-list-link" href="/categories/JavaScript/jQuery/">jQuery</a><span class="category-list-count">1</span></li></ul></li><li class="category-list-item"><a class="category-list-link" href="/categories/Linux/">Linux</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/PHP/">PHP</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Suse/">Suse</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Ubuntu/">Ubuntu</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Vim/">Vim</a><span class="category-list-count">8</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/编程/">编程</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/软件/">软件</a><span class="category-list-count">1</span></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/Android/" style="font-size: 14.75px; color: #65bfa7">Android</a> <a href="/tags/C/" style="font-size: 13.88px; color: #71c1c2">C</a> <a href="/tags/CAS/" style="font-size: 13px; color: #7dc3de">CAS</a> <a href="/tags/Chrome/" style="font-size: 13px; color: #7dc3de">Chrome</a> <a href="/tags/Clean-Code/" style="font-size: 13.88px; color: #71c1c2">Clean Code</a> <a href="/tags/Database/" style="font-size: 13px; color: #7dc3de">Database</a> <a href="/tags/Eclipse/" style="font-size: 13px; color: #7dc3de">Eclipse</a> <a href="/tags/FTP/" style="font-size: 13.88px; color: #71c1c2">FTP</a> <a href="/tags/FreeMarker/" style="font-size: 14.75px; color: #65bfa7">FreeMarker</a> <a href="/tags/Gcc/" style="font-size: 13px; color: #7dc3de">Gcc</a> <a href="/tags/Git/" style="font-size: 14.75px; color: #65bfa7">Git</a> <a href="/tags/Github-Pages/" style="font-size: 13px; color: #7dc3de">Github Pages</a> <a href="/tags/Hexo/" style="font-size: 14.75px; color: #65bfa7">Hexo</a> <a href="/tags/Hibernate/" style="font-size: 13px; color: #7dc3de">Hibernate</a> <a href="/tags/JSP/" style="font-size: 13px; color: #7dc3de">JSP</a> <a href="/tags/JVM/" style="font-size: 14.75px; color: #65bfa7">JVM</a> <a href="/tags/Java/" style="font-size: 14.75px; color: #65bfa7">Java</a> <a href="/tags/JavaMail/" style="font-size: 13px; color: #7dc3de">JavaMail</a> <a href="/tags/JavaScript/" style="font-size: 16.5px; color: #4dbc6f">JavaScript</a> <a href="/tags/Linux/" style="font-size: 13.88px; color: #71c1c2">Linux</a> <a href="/tags/Log/" style="font-size: 13px; color: #7dc3de">Log</a> <a href="/tags/Markdown/" style="font-size: 13.88px; color: #71c1c2">Markdown</a> <a href="/tags/MongoDB/" style="font-size: 20px; color: #1db400">MongoDB</a> <a href="/tags/MySQL/" style="font-size: 13.88px; color: #71c1c2">MySQL</a> <a href="/tags/PHP/" style="font-size: 16.5px; color: #4dbc6f">PHP</a> <a href="/tags/Rhythmbox/" style="font-size: 13px; color: #7dc3de">Rhythmbox</a> <a href="/tags/SSO/" style="font-size: 13px; color: #7dc3de">SSO</a> <a href="/tags/Servlet/" style="font-size: 13px; color: #7dc3de">Servlet</a> <a href="/tags/Shiro/" style="font-size: 13.88px; color: #71c1c2">Shiro</a> <a href="/tags/Spring/" style="font-size: 13.88px; color: #71c1c2">Spring</a> <a href="/tags/Suse/" style="font-size: 13px; color: #7dc3de">Suse</a> <a href="/tags/Thinking-in-Java/" style="font-size: 19.13px; color: #29b61c">Thinking in Java</a> <a href="/tags/Ubuntu/" style="font-size: 17.38px; color: #41ba53">Ubuntu</a> <a href="/tags/Vim/" style="font-size: 18.25px; color: #35b838">Vim</a> <a href="/tags/VirtualBox/" style="font-size: 13px; color: #7dc3de">VirtualBox</a> <a href="/tags/Vsftpd/" style="font-size: 13px; color: #7dc3de">Vsftpd</a> <a href="/tags/jQuery/" style="font-size: 13px; color: #7dc3de">jQuery</a> <a href="/tags/pam-mysql/" style="font-size: 13px; color: #7dc3de">pam_mysql</a> <a href="/tags/小米/" style="font-size: 13px; color: #7dc3de">小米</a> <a href="/tags/软件/" style="font-size: 15.63px; color: #59bd8b">软件</a>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/09/">September 2015</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/08/">August 2015</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/07/">July 2015</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/05/">May 2015</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/04/">April 2015</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/03/">March 2015</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/02/">February 2015</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/12/">December 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/11/">November 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/10/">October 2014</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/09/">September 2014</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/08/">August 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/07/">July 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/06/">June 2014</a><span class="archive-list-count">6</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/05/">May 2014</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/04/">April 2014</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/03/">March 2014</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/02/">February 2014</a><span class="archive-list-count">11</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/01/">January 2014</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/12/">December 2013</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/11/">November 2013</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/08/">August 2013</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/07/">July 2013</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/06/">June 2013</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/05/">May 2013</a><span class="archive-list-count">5</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2013/04/">April 2013</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/03/">March 2012</a><span class="archive-list-count">1</span></li></ul>
    </div>
  </div>


  
    <div class="widget-wrap">
  <h3 class="widget-title">Calendar</h3>
  <div class="widget">
    <div id="g-calendar" class="g-calendar">
        <span class="g-calendar-prev"></span>
		 
        <span class="g-calendar-back"></span>
        <span class="g-calendar-now"></span>
		 
        <span class="g-calendar-next"></span>
        <div class="g-calendar-hd"></div>
        <div class="g-calendar-tit"></div>
        <div class="g-calendar-bd"></div>
    </div>
  </div>
</div>
<script type="text/javascript">
function LGY_calendar(wrapId, options){
    this.oWrap = this.getId(wrapId);
    this.oHead = this.getByClassName('g-calendar-hd',this.oWrap)[0];
    this.oBody = this.getByClassName('g-calendar-bd',this.oWrap)[0];
    this.oTit = this.getByClassName('g-calendar-tit',this.oWrap)[0];
    this.oPrev = this.getByClassName('g-calendar-prev',this.oWrap)[0];
    this.oNext = this.getByClassName('g-calendar-next',this.oWrap)[0];
    this.oNow = this.getByClassName('g-calendar-now',this.oWrap)[0];
    this.oBack = this.getByClassName('g-calendar-back',this.oWrap)[0];
    this.init();
}
LGY_calendar.prototype = {
    ///////////获取ID元素
    getId:function(id){
        return document.getElementById(id);
    },
    ////////获取css类名元素
    getByClassName:function(className,parent){
        var elem = [],
            node = parent != undefined&&parent.nodeType==1?parent.getElementsByTagName('*'):document.getElementsByTagName('*'),
            p = new RegExp("(^|\\s)"+className+"(\\s|$)");
        for(var n=0,i=node.length;n<i;n++){
            if(p.test(node[n].className)){
                elem.push(node[n]);
            }
        }
        return elem;
    },
    //填充日历
    fillDate:function(year,month){
        //本月份第一天是星期几-为显示上个月的天数做铺垫
        var first_day = new Date(year,month,1).getDay(),
        //如果刚好是星期天，则空出一行（显示上个月的天数）
            first_day = first_day == 0?first_day=7:first_day;
        //本月份最后一天是几号
        var final_date = new Date(year,month+1,0).getDate(),
        //上个月的最后一天是几号
            last_date = new Date(year,month,0).getDate(),
        //剩余的格子数--即排在末尾的格子数
            surplus = 42 - first_day - final_date;
        //设置年的链接
        var yearHead = "<a href='/" + "archives/" + year + "/'>" + year + " "+ "</a>"; 
        //设置年的链接
        var monthHead = "";
        var month1 = month + 1;
        if (month1 < 10) {
            monthHead = "<a href='/" + "archives/" + year + "/" + "0" + month1 + "/'>" + " " + month1 + " " + "</a>";
        } else {
            monthHead = "<a href='/" + "archives/" + year + "/" + month1 + "/'>" + " " + month1 + " " + "</a>";
        }
        //设置表头的日历
        this.oHead.innerHTML = yearHead+'年'+monthHead+'月';
        //填充日历执行
        var html = '';
        //上个月的显示天数
        for(var i=0;i<first_day;i++){
            html+='<span class="g-calendar-grey">'+(last_date-(first_day-1)+i)+'</span>';
        }
        //本月的显示天数
        var postdate = new Date("Sun May 04 2014 11:21:38 GMT+0800"); 
        if (true && postdate.getFullYear() == year && postdate.getMonth() == month) { 
            html += '<span>1</span><span>2</span><span>3</span><span><a href="/2014/05/04/mongodb-note-3-creating-updating-and-deleting-documents/" title="mongodb笔记(三) 创建、更新、删除文档">4</a></span><span>5</span><span>6</span><span>7</span><span><a href="/2014/05/08/mongodb-note-4-querying/" title="mongodb笔记(四) 查询">8</a></span><span>9</span><span>10</span><span>11</span><span>12</span><span>13</span><span>14</span><span>15</span><span>16</span><span>17</span><span>18</span><span>19</span><span>20</span><span>21</span><span>22</span><span>23</span><span>24</span><span>25</span><span><a href="/2014/05/26/mongodb-note-5-indexing/" title="mongodb笔记(五) 索引">26</a></span><span>27</span><span><a href="/2014/05/28/mongodb-note-6-aggregation/" title="mongodb笔记(六) 聚合">28</a></span><span>29</span><span>30</span>';
        } else {
            for(var j=0;j<final_date;j++){        
                html+='<span id="d'+(j+1)+'">'+(j+1)+'</span>';
            }
        }
        //下个月的显示天数
        for(var k=0;k<surplus;k++){
            html+='<span class="g-calendar-grey">'+(k+1)+'</span>';
        }
        //fill
        this.oBody.innerHTML = html;
        // 当前状态
        if(year==this.c_year&&this.c_month==month){
            this.oBody.getElementsByTagName('span')[first_day+this.date-1].className='g-calendar-on';
        }

        // 对所有文章遍历,然后将有文章的日期加上链接,如果文章太多的话,生成页面会很大,去掉了
        
    },
    // next切换
    next:function(){
        var _that = this;
        this.oNext.onclick = function(){
            _that.month++;
            if(_that.month>11){
                _that.month = 0;
                _that.year++;
            }
            // 填充日历
            _that.fillDate(_that.year,_that.month);
        };
    },
    // back 切换
    back:function(){
        var _that = this;
        if(this.oBack != undefined) {
            this.oBack.onclick = function(){
                var postdate = new Date("Sun May 04 2014 11:21:38 GMT+0800"); 
                _that.year = postdate.getFullYear();
                _that.month = postdate.getMonth();
                // 填充日历
                _that.fillDate(_that.year,_that.month);
            };
        }
    },
    // now切换
    now:function(){
        var _that = this;
        if(this.oNow != undefined ) {
            this.oNow.onclick = function(){
                var nowDate = new Date(); 
                _that.year = nowDate.getFullYear();
                _that.month = nowDate.getMonth();
                // 填充日历
                _that.fillDate(_that.year,_that.month);
            };
        }
    },
    // prev切换
    prev:function(){
        var _that = this;
        this.oPrev.onclick = function(){
            _that.month--;
            if(_that.month<0){
                _that.month = 11;
                _that.year--;
            }
            // 填充日历
            _that.fillDate(_that.year,_that.month);
        };
    },
    init:function(){
        this.oTit.innerHTML = '<span>日</span><span>一</span><span>二</span><span>三</span><span>四</span><span>五</span><span>六</span>';
        // 获取今天的日历时间
        var now = new Date();
        this.c_year = this.year = now.getFullYear();
        this.c_month = this.month = now.getMonth();
        this.date = now.getDate();
        // 初始化--填充日历
        this.fillDate(this.year,this.month);
        //next切换
        this.next();
        //prev切换
        this.prev();
        //back 切换
        this.back();
        //now 切换
        this.now();
    }
}
new LGY_calendar('g-calendar');
</script>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2015/09/01/javascript-summary/">JavaScript 总结</a>
          </li>
        
          <li>
            <a href="/2015/08/28/javascript-oop-function-expression-and-async/">JavaScript 面向对象程序设计、函数表达式和异步编程</a>
          </li>
        
          <li>
            <a href="/2015/08/28/javascript-reference-type/">JavaScript 引用类型</a>
          </li>
        
          <li>
            <a href="/2015/08/28/javascript-grammar/">JavaScript 基本语法</a>
          </li>
        
          <li>
            <a href="/2015/08/10/java-web/">Java Web 笔记</a>
          </li>
        
      </ul>
    </div>
  </div>


  
    
<div class="widget-wrap">
  <h3 class="widget-title">Recent Comments</h3>
  <ul class="widget ds-recent-comments" data-num-items="5" data-show-avatars="0" data-show-title="1" data-show-time="1"></ul>
</div>
<!-- 需要多说的公用代码 -->


  

</aside>

        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2015 howiefh<br>
      Powered by <a href="http://zespia.tw/hexo/" target="_blank">Hexo</a> and Theme by <a href="https://github.com/howiefh/hexo-theme-landscape-f" target="_blank" title="Landscape-F">Landscape-F</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<!-- 多说公共JS代码 start (一个网页只需插入一次) -->

<script type="text/javascript">
  var duoshuoQuery = {short_name:"howiefh"};
  (function() {
	var ds = document.createElement('script');
	ds.type = 'text/javascript';ds.async = true;
	ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
	ds.charset = 'UTF-8';
	(document.getElementsByTagName('head')[0] 
		|| document.getElementsByTagName('body')[0]).appendChild(ds);
  })();
</script> 

<!-- 多说公共JS代码 end -->

<!-- 百度分享 start -->

<script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":["mshare","douban","bdysc","sqq","qq","hi","baidu","huaban","youdao","sdo","mail","xg","diandian","fx","copy","print"],"bdPic":"","bdStyle":"1","bdSize":"16"},"share":{},"image":{"viewList":["qzone","tsina","tqq","renren","weixin"],"viewText":"分享到：","viewSize":"16"}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>

<!-- 百度分享 end -->

<!--
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="/js/jquery.min.js"></script>
-->
<script src="/js/jquery.min.js" type="text/javascript"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css" type="text/css">
  <script src="/fancybox/jquery.fancybox.pack.js" type="text/javascript"></script>


<div class="bottom-btn">

	<a class="icon-gotop" href="javascript:void(0)" title="返回顶部"></a>
	<script src="/js/gotop.js" type="text/javascript"></script>
	<!--
	<script src="/js/gotop.js"></script>
	-->


	<a class="icon-toc-toggle" href="javascript:void(0)" title="文章目录"></a>
	<!--
	<script src="/js/toc_aside_toggle.js"></script>
	-->

</div>
<script src="/js/toc_aside_toggle.js" type="text/javascript"></script>


<script src="/js/script.js" type="text/javascript"></script>

  </div>
</body>
</html>
